package org.example.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库连接工具类
 */
public class DatabaseConnection {
    private static Connection connection = null;

    /**
     * 获取数据库连接
     *
     * @return Connection对象
     */
    public static Connection getConnection() {
        try {
            // 加载数据库驱动
            Class.forName(DatabaseConfig.DB_DRIVER);
            
            // 建立数据库连接
            connection = DriverManager.getConnection(
                DatabaseConfig.DB_URL,
                DatabaseConfig.DB_USERNAME,
                DatabaseConfig.DB_PASSWORD
            );
            
            System.out.println("数据库连接成功！");
        } catch (ClassNotFoundException e) {
            System.err.println("找不到数据库驱动类：" + e.getMessage());
        } catch (SQLException e) {
            System.err.println("数据库连接失败：" + e.getMessage());
        }
        
        return connection;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
                System.out.println("数据库连接已关闭！");
            } catch (SQLException e) {
                System.err.println("关闭数据库连接失败：" + e.getMessage());
            }
        }
    }
    
    /**
     * 测试数据库连接
     */
    public static void testConnection() {
        Connection conn = getConnection();
        if (conn != null) {
            System.out.println("数据库连接测试成功！");
            closeConnection();
        } else {
            System.err.println("数据库连接测试失败！");
        }
    }
}